(function() {
    'use strict';

    angular
        .module('app')
        .factory('AuthServerProvider', AuthServerProvider);

    AuthServerProvider.$inject = ['$http', '$localStorage' ,'$rootScope','Account'];

    function AuthServerProvider ($http, $localStorage,$rootScope,Account) {
        var service = {
            getToken: getToken,
            hasValidToken: hasValidToken,
            login: login,
            logout: logout,
            pwdup: pwdup
        };

        return service;

        function getToken () {
            var token = $localStorage.authenticationToken;
            return token;
        }

        function hasValidToken () {
            var token = this.getToken();
            return !!token;
        }

        function login (user) {
            var data = 'code=' + encodeURIComponent(user.code) +
                '&password=' + encodeURIComponent(user.password) +
                '&remember-me=' + user.rememberMe + '&submit=Login';
            return $http.post('api/authentication', data, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (response) {
                return response;
            });
        }

        function logout () {
            // logout from the server
            return $http.post('api/logout').success(function (response) {
                delete $localStorage.authenticationToken;
                // to get a new csrf token call the api
                $rootScope.user=null;
                return response;
            });
        }
        
        function pwdup(srcpwd,newpwd){
	        return $http.post('api/account/change_password', "srcpwd="+srcpwd+"&newpwd="+newpwd, {
	            headers: {
	                'Content-Type': 'application/x-www-form-urlencoded'
	            }
	        }).success(function (response) {
	            return response;
	        });
        }
    }
})();
